//
//  AppGlobalClass.m
//  鱼鱼APP
//
//  Created by User on 15/1/13.
//  Copyright (c) 2015年 User. All rights reserved.
//

#import "AppGlobalClass.h"

#import <CommonCrypto/CommonDigest.h>

static AFHTTPRequestOperationManager *__manager;

@implementation AppGlobalClass

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}


+ (NSString *)SharedURL:(NSString *)url
{
    return Index_Url_Test;
}

+ (NSString *) SharedURL
{
    return Index_Url_Test; // Index_Url_Test
}

+ (NSString *) SharedNullToNSString : (id) object
{
    if ([object isKindOfClass:[NSString class]])
    {
        return object;
    }    
    else return @"";
}


/**
 *  获取数据的方法（POST方法）
 *
 *  @param actionUrlStr   每个接口的地址
 *  @param dic            储存键值对的字典
 *  @param viewController 加载在哪个view上
 *  @param success        成功返回的数据
 *  @param failure        失败的参数
 *  @param networkerror   网络错误
 *
 *  @return 返回键值对
 */

+(NSDictionary *)PostDataWithNSstring : (NSString *)actionUrlStr
                       withDictionary : (NSMutableDictionary *) dic
                 withUIViewController : (UIViewController *)viewController
                              success : (void (^)(NSDictionary* dictionary))success
                              failure : (void (^)(NSError *error))failure
                         networkerror : (void (^)(NSString *networkerror))networkerror
{
    NSString *URL = [NSString stringWithFormat:@"%@%@",[self SharedURL:actionUrlStr],actionUrlStr];
    
    if ( [CheckNetWork isExistenceNetwork] )
    {
        // AFNetworking 2.3.3
        AFHTTPRequestOperationManager *httpClient = [AFHTTPRequestOperationManager manager];
        __manager = httpClient;
        [httpClient POST:URL
              parameters:dic
                 success:^(AFHTTPRequestOperation *operation, id responseObject) {
                     NSDictionary *dictionary = responseObject;
                     if(dictionary)
                     {
                         success(dictionary);
                     }
                 }
                 failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                 }];
    }
    return nil;
}

+(NSDictionary *)PostDataWithNSstring : (NSString *)actionUrlStr
                       withDictionary : (NSDictionary *) dic
                              success : (void (^)(NSDictionary* dictionary))success
                              failure : (void (^)(NSError *error))failure
                         networkerror : (void (^)(NSString *networkerror))networkerror
{
    NSString *URL = [NSString stringWithFormat:@"%@%@",[self SharedURL:actionUrlStr],actionUrlStr];
    URL = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    if ( [CheckNetWork isExistenceNetwork] )
    {
        // AFNetworking 2.3.3
        AFHTTPRequestOperationManager *httpClient = [AFHTTPRequestOperationManager manager];
        __manager = httpClient;

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
            [httpClient POST:URL
                  parameters:dic
                     success:^(AFHTTPRequestOperation *operation, id responseObject) {
                         NSLog(@"======%@",operation.responseString);
                         NSDictionary *dictionary = responseObject;
                         NSLog(@"======%@",dictionary);
                         if(dictionary)
                         {
                             success(dictionary);
                             
                         }
                         else
                         {
                             ALERT_VIEW(@"服务器异常");
                         }
                     }
                     failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                         failure(error);
                         
                         NSDictionary *dic = [AppGlobalClass dictionaryWithJsonString:operation.responseString];
                         
                         if (dic) {
                             NSString *message = [dic objectForKey:@"message"];
                             if (message) {
                                 if ([message isEqualToString:@"登录失败，请重新登录"]) {
                                     [[NSNotificationCenter  defaultCenter] postNotificationName:@"reLogin" object:nil];
                                 }
                                 else{
                                     UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                                     
                                     MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:TRUE];
                                     hud.mode = MBProgressHUDModeText;
                                     hud.labelText = message;
                                     hud.labelFont = [UIFont systemFontOfSize:13.0f];
                                     [hud hide:TRUE afterDelay:2.0f];
                                     
                                 }
                             }
                             
                         }
                         else
                         {
                             if(![actionUrlStr isEqualToString:LOGIN_URL])
                             {
                                 UIWindow *window = [[UIApplication sharedApplication]keyWindow];
                                 
                                 MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:TRUE];
                                 hud.mode = MBProgressHUDModeText;
                                 hud.labelText = @"连接服务器失败";
                                 hud.labelFont = [UIFont systemFontOfSize:13.0f];
                                 [hud hide:TRUE afterDelay:2.0f];
                                 
                             }
                             
                         }

                         
                     }];
        });
    }
    else
    {
        networkerror(@"网络异常");
        
       
        
        UIWindow *window = [[UIApplication sharedApplication]windows][0];
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:TRUE];
            hud.mode = MBProgressHUDModeText;
            hud.labelText = @"网络异常";
            hud.labelFont = [UIFont systemFontOfSize:13.0f];
            [hud hide:TRUE afterDelay:2.0f];
        }
    return nil;
}

+ (NSString *)md5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);// This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (void)deleteCookie
{
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies])
    {
        [storage deleteCookie:cookie];
    }
}

+(void)cancleRequest
{
    if (__manager.operationQueue!=nil) {
        [__manager.operationQueue cancelAllOperations];
        __manager = nil;
    }
}

+(NSString *)PostImagesToServer:(NSString *) strUrl dicPostParams:(NSMutableDictionary *)params dicImages:(NSMutableDictionary *) dicImages{
    NSString * res;
    
    
    //分界线的标识符
    NSString *TWITTERFON_FORM_BOUNDARY = @"AaB03x";
    //根据url初始化request
    //NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
    NSString *URL = [NSString stringWithFormat:@"%@%@",[self SharedURL],strUrl];
    URL = [URL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:URL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //分界线 --AaB03x
    NSString *MPboundary=[[NSString alloc]initWithFormat:@"--%@",TWITTERFON_FORM_BOUNDARY];
    //结束符 AaB03x--
    NSString *endMPboundary=[[NSString alloc]initWithFormat:@"%@--",MPboundary];
    //要上传的图片
    UIImage *image;//=[params objectForKey:@"pic"];
    //得到图片的data
    //NSData* data = UIImagePNGRepresentation(image);
    //http body的字符串
    NSMutableString *body=[[NSMutableString alloc]init];
    //参数的集合的所有key的集合
    NSArray *keys= [params allKeys];
    
    //遍历keys
    for(int i=0;i<[keys count];i++) {
        //得到当前key
        NSString *key=[keys objectAtIndex:i];
        //如果key不是pic，说明value是字符类型，比如name：Boris
        //if(![key isEqualToString:@"pic"]) {
        //添加分界线，换行
        [body appendFormat:@"%@\r\n",MPboundary];
        //添加字段名称，换2行
        [body appendFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n",key];
        //[body appendString:@"Content-Transfer-Encoding: 8bit"];
        //添加字段的值
        [body appendFormat:@"%@\r\n",[params objectForKey:key]];
        //}
    }
    ////添加分界线，换行
    //[body appendFormat:@"%@\r\n",MPboundary];
    
    //声明myRequestData，用来放入http body
    NSMutableData *myRequestData=[NSMutableData data];
    //将body字符串转化为UTF8格式的二进制
    [myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
    
    //循环加入上传图片
    keys = [dicImages allKeys];
    for(int i = 0; i< [keys count] ; i++){
        //要上传的图片
        image = [dicImages objectForKey:[keys objectAtIndex:i ]];
        //得到图片的data
        NSData* data =  UIImageJPEGRepresentation(image, 0.0);
        NSMutableString *imgbody = [[NSMutableString alloc] init];
        //此处循环添加图片文件
        //添加图片信息字段
        //声明pic字段，文件名为boris.png
        //[body appendFormat:[NSString stringWithFormat: @"Content-Disposition: form-data; name=\"File\"; filename=\"%@\"\r\n", [keys objectAtIndex:i]]];
        
        ////添加分界线，换行
        [imgbody appendFormat:@"%@\r\n",MPboundary];
        [imgbody appendFormat:@"Content-Disposition: form-data; name=\"File%d\"; filename=\"%@.jpg\"\r\n", i, [keys objectAtIndex:i]];
        //声明上传文件的格式
        [imgbody appendFormat:@"Content-Type: application/octet-stream; charset=utf-8\r\n\r\n"];
        
        NSLog(@"上传的图片：%d  %@", i, [keys objectAtIndex:i]);
        
        //将body字符串转化为UTF8格式的二进制
        //[myRequestData appendData:[body dataUsingEncoding:NSUTF8StringEncoding]];
        [myRequestData appendData:[imgbody dataUsingEncoding:NSUTF8StringEncoding]];
        //将image的data加入
        [myRequestData appendData:data];
        [myRequestData appendData:[ @"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }
    //声明结束符：--AaB03x--
    NSString *end=[[NSString alloc]initWithFormat:@"%@\r\n",endMPboundary];
    //加入结束符--AaB03x--
    [myRequestData appendData:[end dataUsingEncoding:NSUTF8StringEncoding]];
    
    //设置HTTPHeader中Content-Type的值
    NSString *content=[[NSString alloc]initWithFormat:@"multipart/form-data; boundary=%@",TWITTERFON_FORM_BOUNDARY];
    //设置HTTPHeader
    [request setValue:content forHTTPHeaderField:@"Content-Type"];
    //[request setValue:@"keep-alive" forHTTPHeaderField:@"connection"];
    //[request setValue:@"UTF-8" forHTTPHeaderField:@"Charsert"];
    //设置Content-Length
    [request setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[myRequestData length]] forHTTPHeaderField:@"Content-Length"];
    //设置http body
    [request setHTTPBody:myRequestData];
    //http method
    [request setHTTPMethod:@"POST"];
    
    //建立连接，设置代理
    //NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    //设置接受response的data
    NSData *mResponseData;
    NSError *err = nil;
    mResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
    
    if(mResponseData == nil){
        NSLog(@"err code : %@", [err localizedDescription]);
    }
    res = [[NSString alloc] initWithData:mResponseData encoding:NSUTF8StringEncoding];
    /*
     if (conn) {
     mResponseData = [NSMutableData data];
     mResponseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&err];
     
     if(mResponseData == nil){
     NSLog(@"err code : %@", [err localizedDescription]);
     }
     res = [[NSString alloc] initWithData:mResponseData encoding:NSUTF8StringEncoding];
     }else{
     res = [[NSString alloc] init];
     }*/
    NSLog(@"服务器返回：%@", res);
    return res;
}

@end
